package cn.lixin.hrm.details;

import cn.lixin.hrm.cllient.SystemFeignClient;
import cn.lixin.hrm.domain.*;
import cn.lixin.hrm.mapper.LoginUserMapper;
import cn.lixin.hrm.domain.LoginUser;
import cn.lixin.hrm.domain.Permission;
import cn.lixin.hrm.mapper.LoginUserMapper;
import cn.lixin.hrm.util.AjaxResult;
import com.alibaba.fastjson.JSON;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class HrmUserDetailsService implements UserDetailsService{
    @Autowired
    private LoginUserMapper loginUserMapper;
    @Autowired
    private SystemFeignClient systemFeignClient;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询数据库
        LoginUser loginUser = loginUserMapper.loadUserByUsername(username);
        if(loginUser == null)
            throw  new RuntimeException("查无此人");
        //查询用户的权限
        List<Permission> list = loginUserMapper.getUserPermissions(loginUser.getId());
        //创建一个User对象
        ArrayList<GrantedAuthority> permissons = new ArrayList<>();
        list.stream().forEach(permission -> {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission.getSn());
            permissons.add(authority);
        });
        /**
         * 这里因为已经认证过了，我们把员工和店铺信息查出来转成json字符串存到username字段中
         *
         */
        if (loginUser.getType()==0){ // 员工
            AjaxResult result = systemFeignClient.getUserInfo(loginUser.getUsername());
            if (result.isSuccess()){
                loginUser.setUsername(result.getResultObj().toString());
            }
        }
        User user = new User(loginUser.getUsername(), loginUser.getPassword(), permissons);
        return user;
    }
}
